package com.wn26.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.wn26.bean.Goods;
import com.wn26.service.GoodsService;
import com.wn26.service.impl.GoodsServiceImpl;

/**
 * Servlet implementation class ListGoodsServlet
 */
@WebServlet("/ListGoodsServlet")
public class ListGoodsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ListGoodsServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// --查询商品
		GoodsService gs = new GoodsServiceImpl();

		try {
			List<Goods> goodsList = gs.listGoods();
			for (Goods goods : goodsList) {
				System.out.println(goods);
			}
			// --把List转成JsonArray
			JSONArray array = JSON.parseArray(JSON.toJSONString(goodsList));
			// --把JsonArray变成Json字符串
			String content = array.toJSONString();
			// --把Json字符串写给前端
			response.getWriter().write(content);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
